package com.servicelive;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.TimeZone;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.servicelivedb.ServiceliveDB;
import com.servicelivedb.data.Block;
import com.servicelivedb.data.Customer;
import com.servicelivedb.data.Door;
import com.wavemaker.runtime.RuntimeAccess;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.service.annotations.ExposeToClient;

/**
 * This is a client-facing service class. All public methods will be exposed to
 * the client. Their return values and parameters will be passed to the client
 * or taken from the client, respectively. This will be a singleton instance,
 * shared between all requests.
 * 
 * To log, call the superclass method log(LOG_LEVEL, String) or log(LOG_LEVEL,
 * String, Exception). LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to
 * modify your log level. For info on these levels, look for tomcat/log4j
 * documentation
 */
@ExposeToClient
public class ServiceLiveCommonService extends JavaServiceSuperClass {
	/*
	 * Pass in one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log
	 * level; recommend changing this to FATAL or ERROR before deploying. For
	 * info on these levels, look for tomcat/log4j documentation
	 */
	public ServiceLiveCommonService() {
		super(INFO);
	}

	public String sampleJavaOperation(OrderedItemDetails details) {
		String result = null;
		try {
			log(INFO, "Starting sample operation");
			result = "Hello World";
			log(INFO, "Returning " + result);
		} catch (Exception e) {
			log(ERROR, "The sample java service operation has failed", e);
		}
		return result;
	}

	public Block getBlock(Session session, String blockName, Integer projectId) {
		Block block = null;

		try {
			Query query = session
					.createQuery(" from Block block where block.blockName= :blockName and block.project.projectId= :projectId");
			query.setString("blockName", blockName);
			query.setInteger("projectId", projectId);
			block = (Block) query.uniqueResult();
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return block;

	}

	public Door getDoor(Session session, Integer blockId, String doorName,
			Integer projectId) {
		Door door = null;

		try {
			Query query = session
					.createQuery(" from Door door where door.doorName= :doorName and door.block.blockId=:blockId and door.block.project.projectId= :projectId");
			query.setString("doorName", doorName);
			query.setInteger("blockId", blockId);
			query.setInteger("projectId", projectId);
			door = (Door) query.uniqueResult();

		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return door;

	}

	public String updateAccount(Customer customer, Boolean isVendor)
			throws Exception {
		String result = null;

		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");

		try {

			db.begin();

			Session session = db.getDataServiceManager().getSession();

			Customer newCustomer = (Customer) session.get(Customer.class,
					customer.getCustomerId());

			newCustomer.setName(customer.getName());
			newCustomer.setUpdatedBy(customer.getName());
			Calendar startingCalendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
			
			newCustomer.setUpdatedDt(startingCalendar.getTime());
			newCustomer.setActive(customer.getActive());
			newCustomer.setPassword(customer.getPassword());
			newCustomer.setAddress(customer.getAddress());
			newCustomer.setPrimaryPhone(customer.getPrimaryPhone());
			System.out.println("block==" + customer.getBlock().getBlockName());
			Block block = getBlock(session, customer.getBlock().getBlockName(),
					newCustomer.getProject().getProjectId());
			if (block == null) {
				result = "Block could not be found";
				throw new Exception(result);
			}
			newCustomer.setBlock(block);
			System.out.println("door==" + customer.getDoor().getDoorName());
			Door door = getDoor(session, block.getBlockId(), customer.getDoor()
					.getDoorName(), newCustomer.getProject().getProjectId());
			if (door == null) {
				result = "Door could not be found";
				throw new Exception(result);
			}
			newCustomer.setDoor(door);

			session.saveOrUpdate(newCustomer);

			log(INFO, "Starting sample operation");

			db.commit();

			result = "Account updated successfully";
		} catch (Exception e) {
			db.rollback();
			log(ERROR, "The sample java service operation has failed", e);
			throw e;
		}
		return result;
	}

	public static class OrderedItemDetails {
		private Integer itemId;
		private BigDecimal quantity;
		private String itemName;

		private String desc;
		private Float orderedPrice;

		public Integer getItemId() {
			return itemId;
		}

		public String getItemName() {
			return itemName;
		}

		public void setItemName(String itemName) {
			this.itemName = itemName;
		}

		public void setItemId(Integer itemId) {
			this.itemId = itemId;
		}

		public BigDecimal getQuantity() {
			return quantity;
		}

		public void setQuantity(BigDecimal quantity) {
			this.quantity = quantity;
		}

		public String getDesc() {
			return desc;
		}

		public void setDesc(String desc) {
			this.desc = desc;
		}

		public Float getOrderedPrice() {
			return orderedPrice;
		}

		public void setOrderedPrice(Float orderedPrice) {
			this.orderedPrice = orderedPrice;
		}

	}
}
